#include <stdio.h>
#include <inttypes.h>
#include <assert.h>
#include <stdint.h>
#include <ctype.h>

// Работает на любом инпуте. Не использует дополнительтной памяти.
// 'Протестирована' функция деления на 3. 

int is_div_by_3(char *number) {
	assert(number);
	int64_t tmp_num = 0;
	do {
		tmp_num = 0;
		int64_t i = 0;
		for (i = 0; number[i] != '\0'; ++i) {
			tmp_num += number[i] - '0';
		}	
		sprintf(number, "%" PRId64, tmp_num);

	} while (tmp_num >= 10);

	if (tmp_num == 0 || tmp_num == 3 || tmp_num == 9)
		return 1;
	return 0;
}

int is_div_by_5(char *number) {
	assert(number);
	int i = 0;
	if (number[i] == '-')
		i++;
	while (isdigit(number[i]))
		i++;

	if (number[i - 1] != '5' && number[i - 1] != '0')
		return 0;

	return 1;
}

int is_number(char *number) {
	assert(number);
	uint64_t i = 0;
	if (number[i] == '-') {
		if (!isdigit(number[i + 1]))
			return 0;
		i++;
	}

	for (; number[i] != '\0' && !isspace(number[i]); ++i)
		if (!isdigit(number[i]))
			return 0;	
	return 1;
}

int main(int argc, char **argv) {
	char *input_file = NULL;
	char *output_file = "bb.out";
	if (argc != 2 && argc != 4) {
		printf("Usage: bizzbuzz input_file [-o <output_file>]\n");
		return -1;
	}
	else {
		input_file = argv[1];
		if (argc == 4) {
			output_file = argv[3];
		}
	}
	char input_buffer[1000000] = {0};
	printf("input_file = %s, output_file = %s", input_file, output_file);
	FILE *fin = fopen(input_file, "r");
	FILE *fout = fopen(output_file, "w");
	assert(fin);
	for (;;) {
		if (fscanf(fin, "%999999[^ ^\n]%*c", input_buffer) == EOF)
			break;
		if (!is_number(input_buffer))
			return -1;
		printf("[%s]\n", input_buffer);
		if (is_div_by_5(input_buffer))
			fprintf(fout, "buzz");
		if (is_div_by_3(input_buffer))
			fprintf(fout, "bizz");
			
	}


	fclose(fin);
	fclose(fout);
	
	return 0;
}
